package org.dbcopy.util;

import org.dbcopy.domain.ApplicationParameters;
import org.dbcopy.domain.Table;

import java.sql.*;
import java.util.*;


public class DbUtils{
	private ApplicationParameters utilParameters;
	private Connection connection;
	
	public DbUtils(ApplicationParameters ap){
		utilParameters = ap;
		loadDriver();
	}
	
	private void loadDriver(){
		try {
			Class.forName(utilParameters.getDriverName()).newInstance();
		} catch(Exception e){
			System.err.println("Error in loading database driver: "+utilParameters.getDriverName());
		}
	}
	
	public void closeConnection() {
		try {
			if (connection != null) connection.close(); 
		} catch (Exception e)	{
			System.err.println("Unable to perform database statement");
			connection = null;
		}
	}
	
	public Connection openConnection() throws Exception{
		try {
			closeConnection();
			connection = DriverManager.getConnection(utilParameters.getDbUrl(), 
													utilParameters.getNameOfUser(), 
													utilParameters.getPassword());
		} catch (Exception e) {
			System.err.println("Error in opening connection with url: " + utilParameters.getDbUrl());
			closeConnection();
			e.printStackTrace();
			throw e;
		}		
		return connection; 		
	}
	
	public List<Table> getAllTables(){
		// todo
		List<Table> allTables = new ArrayList<Table>();
		Table tableMan = new Table("man");
		Table tableJob = new Table("job");
		allTables.add(tableJob);
		allTables.add(tableMan);
		return allTables;
	}
	
	public ResultSet getAllData(Table table) throws Exception{
		ResultSet statementResult = null;
		try {
			Statement selectStatement = connection.createStatement();
			statementResult = selectStatement.executeQuery("SELECT * FROM " + table.getName());
		} catch (Exception e) {
			System.err.println("Unable to perform database statement");
			throw e;
		}
		return statementResult;
	}
}